import { App, createVNode, render, ComponentPublicInstance } from 'vue'
import contextMenu from '@/components/common/ContextMenu/ContextMenu.vue'
import { CustomMouseMenuOptions } from '@/components/common/ContextMenu/types'
import { createClassDom } from '@/hook/dom'

contextMenu.install = (app: App): void => {
  app.component(contextMenu.name, contextMenu)
}

const ContextMenu = (
  options: CustomMouseMenuOptions
): ComponentPublicInstance => {
  const className = 'context_menu__container'
  let container: HTMLElement
  if (document.querySelector(`.${className}`)) {
    container = document.querySelector(`.${className}`) as HTMLElement
  } else {
    container = createClassDom('div', className)
  }
  const vm = createVNode(contextMenu, options, null)
  render(vm, container)
  document.body.append(container)
  const vCpn = vm.component?.proxy as ComponentPublicInstance<
    typeof contextMenu
  >
  vCpn.show()
  return vCpn
}

class ScrollLeft {
  speed: number
  scrollRef: HTMLDivElement
  beginRef: HTMLDivElement
  endRef: HTMLDivElement
  beginRefWidth: number
  endRefWidth: number
  scrollRefWidth: number
  MyMar: any
  scrolling: boolean
  constructor(
    scrollRef: HTMLDivElement,
    beginRef: HTMLDivElement,
    endRef: HTMLDivElement,
    speed = 30
  ) {
    this.scrollRef = scrollRef
    this.beginRef = beginRef
    this.endRef = endRef
    this.speed = speed
    this.init()
    this.eventListner()
    this.scorllLeft()
  }

  private init() {
    this.MyMar = null
    this.scrolling = false
    this.beginRefWidth = this.beginRef.offsetWidth
    this.endRefWidth = this.endRef.offsetWidth
    this.scrollRefWidth = this.scrollRef.offsetWidth
  }

  private scorllLeft() {
    if (this.scrolling) return
    // 当文字少于宽度时无法触发
    if (this.beginRefWidth < this.scrollRefWidth + 5) return
    this.endRef.innerHTML = this.beginRef.innerHTML
    this.scrolling = true
    this.MyMar = setInterval(this.Marquee.bind(this), this.speed)
  }

  public Marquee() {
    if (this.scrollRef.scrollLeft < this.beginRefWidth) {
      this.scrollRef.scrollLeft += 1
    } else {
      clearInterval(this.MyMar)
      this.scrolling = false
      this.scrollRef.scrollLeft = 0
    }
  }

  public eventListner() {
    this.scrollRef.onmouseover = () => {
      this.scorllLeft()
    }
  }
}

export { ScrollLeft, ContextMenu }
